package com.tekj.cxqcb.view.Module.activity.Order;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.tekj.cxqcb.R;
import com.tekj.cxqcb.operation.BusinessDao;
import com.tekj.cxqcb.operation.resultBean.PubStatusBean;
import com.tekj.cxqcb.operation.resultBean.UploadFiles;
import com.tekj.cxqcb.view.Module.adapter.Proposal2Adapter;
import com.tekj.cxqcb.view.Module.bean.ImageBean;
import com.tekj.cxqcb.view.Module.bean.UpdateContractBean;
import com.tekj.cxqcb.view.Module.decoration.SpacesItemDecoration;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import common.base.activity.BaseActivity;
import common.base.operationHelper.Bean.BindingViewBean;
import common.tool.Tools;
import common.widget.ZoomImageView;
import es.dmoral.toasty.Toasty;

import static com.tekj.cxqcb.view.Module.activity.Order.CarOrderDetailsActivity.orderData;
import static com.tekj.cxqcb.view.Module.activity.Order.NewOrdersTwoActivity.ImgString;

/**
 * 合同信息
 */
public class ContractInformationActivity extends BaseActivity {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_l)
    TextView tvL;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_r)
    ImageView ivR;
    @BindView(R.id.tv_r)
    TextView tvR;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.rl_title_bg)
    RelativeLayout rlTitleBg;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_address2)
    TextView tvAddress2;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_sl1)
    TextView tvSl1;
    @BindView(R.id.rv_hgz)
    RecyclerView rvHgz;
    @BindView(R.id.tv_sl2)
    TextView tvSl2;
    @BindView(R.id.rv_hkk)
    RecyclerView rvHkk;
    @BindView(R.id.rv_qtzl)
    RecyclerView rvQtzl;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.tv_submission)
    TextView tvSubmission;

    private List<LocalMedia> localMedias, localMedias2, localMedias3;
    private Proposal2Adapter adapter, adapter2, adapter3;
    private List<ImageBean> imgs1, imgs2, imgs3;

    BusinessDao businessDao;
    UpdateContractBean updateContractBean;

    private String[] urls = {
            "https://apk.cars-cxqc.com/%E5%90%88%E6%A0%BC%E8%AF%81.jpg",
            "https://apk.cars-cxqc.com/%E8%BF%98%E6%AC%BE%E5%8D%A1.jpg"};

    @Override
    public void init() {
        businessDao = new BusinessDao(activity, activity);
        tvTitle.setText("合同信息");

        tvName.setText(CarOrderDetailsActivity.orderData.getOrder().getSalesName());
        tvPhone.setText(CarOrderDetailsActivity.orderData.getOrder().getSalesPhone());
        tvAddress.setText(CarOrderDetailsActivity.orderData.getOrder().getStoreAddress());
//        tvAddress2.setText(CarOrderDetailsActivity.orderData.getOrder().getStoreAddress());

        tvTime.setText(CarOrderDetailsActivity.orderData.getOrder().getAztime());

        updateContractBean = new UpdateContractBean();
        updateContractBean.setId(CarOrderDetailsActivity.orderData.getOrder().getId());

        initList();
    }

    @Override
    public int setLayout() {
        return R.layout.activity_contract_information;
    }

    @Override
    public void initLoadStart() {
        showDialog();
    }

    @Override
    public void initLoadEnd() {
        dialog.dismiss();
    }

    @Override
    public void initBindingView(Object mBean) {
        BindingViewBean bindingViewBean = (BindingViewBean) mBean;
        switch (bindingViewBean.getmEnumStatus()) {
            case 多文件上传:
                UploadFiles uploadFiles = (UploadFiles) bindingViewBean.getBean();
                if (!uploadFiles.getCode().equals("0000000")) {
                    Toasty.normal(activity, uploadFiles.getMsg()).show();
                    return;
                }
                if (uploadFiles.getTypeName().equals("合格证")) {
                    addImg(uploadFiles, imgs1);
                } else if (uploadFiles.getTypeName().equals("还款卡")) {
                    addImg(uploadFiles, imgs2);
                } else if (uploadFiles.getTypeName().equals("其他资料")) {
                    addImg(uploadFiles, imgs3);
                }
                break;

            case 合同信息修改:

                PubStatusBean pubStatusBean = (PubStatusBean) bindingViewBean.getBean();
                if (pubStatusBean.getCode().equals("0000000")) {
                    finish();
                }
                Toasty.normal(activity, pubStatusBean.getMsg()).show();
                break;
        }

    }

    @OnClick({R.id.ll_back, R.id.tv_time, R.id.tv_sl1, R.id.tv_sl2, R.id.tv_submission})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_time:
                Tools.newTimeDialog(tvTime, activity);
                break;
            case R.id.tv_sl1:
                showPop(urls[0]);
                break;
            case R.id.tv_sl2:
                showPop(urls[1]);
                break;
            case R.id.tv_submission:

                if (orderData.getOrder().getOrderStatus() != 6) {
                    Toasty.normal(activity, "合同信息未审核或已通过").show();
                    return;
                }

                if (tvTime.getText().toString().trim().equals("")) {
                    Toasty.normal(activity, "请选择时间").show();
                    return;
                }
                updateContractBean.setAztime(tvTime.getText().toString());
                if (imgs1.size() == 0 || imgs2.size() == 0) {
                    Toasty.normal(activity, "请先上传所需图片").show();
                    return;
                }
                updateContractBean.setQualified(ImgString(imgs1));
                updateContractBean.setRepayment(ImgString(imgs2));
                updateContractBean.setInformation(ImgString(imgs3));
                updateContractBean.setContractRemark(etRemark.getText().toString().trim());

                Tools.showNormalDialogOne(activity, "合同信息", "是否修改", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        businessDao.UpdateContract(updateContractBean);
                    }
                }, null);

                break;
        }
    }

    /**
     * 初始化List，adapter
     */
    public void initList() {
        localMedias = new ArrayList<>();
        localMedias2 = new ArrayList<>();
        localMedias3 = new ArrayList<>();

        imgs1 = new ArrayList<>();
        imgs2 = new ArrayList<>();
        imgs3 = new ArrayList<>();

        if (CarOrderDetailsActivity.orderData.getOrder().getQualified() != null) {
            getImges(CarOrderDetailsActivity.orderData.getOrder().getQualified(), imgs1, localMedias);
        }
        if (CarOrderDetailsActivity.orderData.getOrder().getRepayment() != null) {
            getImges(CarOrderDetailsActivity.orderData.getOrder().getRepayment(), imgs2, localMedias2);
        }
        if (CarOrderDetailsActivity.orderData.getOrder().getInformation() != null) {
            getImges(CarOrderDetailsActivity.orderData.getOrder().getInformation(), imgs3, localMedias3);
        }
        adapter = new Proposal2Adapter(activity, localMedias, localMedias.size() + 1);
        adapter2 = new Proposal2Adapter(activity, localMedias2, localMedias2.size() + 1);
        adapter3 = new Proposal2Adapter(activity, localMedias3, localMedias3.size() + 1);

        initAdaper(adapter, localMedias, rvHgz, imgs1, 1001);
        initAdaper(adapter2, localMedias2, rvHkk, imgs2, 1002);
        initAdaper(adapter3, localMedias3, rvQtzl, imgs3, 1003);

    }

    /**
     * 初始化adapter方法
     *
     * @param adapter
     * @param localMedias
     * @param recyclerView
     * @param imgs
     * @param code
     */
    public void initAdaper(final Proposal2Adapter adapter, final List<LocalMedia> localMedias,
                           RecyclerView recyclerView, final List<ImageBean> imgs, final int code) {


        adapter.setOnCallbackListener(new Proposal2Adapter.OnCallbackListener() {
            @Override
            public void onAddPhotoClick() {
                //添加图片
                Tools.InitPictureSelector(activity, false, code,
                        getLocalMedias(localMedias), 9 - localMedias.size());
            }

            @Override
            public void onPicturePreview(int position) {
                //图片预览
//                PictureSelector.create(activity).externalPicturePreview(position, localMedias);
            }

            @Override
            public void onPictureDelete(int position) {
                localMedias.remove(position);
                imgs.remove(position);
                adapter.setList(localMedias, localMedias.size() + 1);
            }
        });

        recyclerView.setLayoutManager(new GridLayoutManager(activity, 3));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new SpacesItemDecoration(10));
    }


    /**
     * 获取除已上传图片（新增的本地图片）
     *
     * @return
     */
    public static List<LocalMedia> getLocalMedias(List<LocalMedia> localMedias) {
        List<LocalMedia> list = new ArrayList<>();
        for (int i = 0; i < localMedias.size(); i++) {
            if (!localMedias.get(i).getCompressPath().startsWith("http")) {
                list.add(localMedias.get(i));
            }
        }
        return list;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> lists;
        List<File> list = new ArrayList<>();
        if (resultCode == RESULT_OK) {
            lists = PictureSelector.obtainMultipleResult(data);
            switch (requestCode) {
                case 1001:
                    upImg(lists, list, localMedias, adapter, "合格证");
                    break;
                case 1002:
                    upImg(lists, list, localMedias2, adapter2, "还款卡");
                    break;
                case 1003:
                    upImg(lists, list, localMedias3, adapter3, "其他资料");
                    break;
            }
        }
    }

    /**
     * @param uploadFiles
     * @param imgs
     */
    void addImg(UploadFiles uploadFiles, List<ImageBean> imgs) {
        if (imgs == null) {
            return;
        }
        String[] files = uploadFiles.getData().getUploadFilePath().split(",");
        Iterator it = imgs.iterator();
        while (it.hasNext()) {
            ImageBean m = (ImageBean) it.next();
            if (!m.isInitial()) {
                it.remove();
            }
        }
        for (int i = 0; i < files.length; i++) {
            imgs.add(new ImageBean(files[i], false));
        }
    }

    /**
     * 添加图片
     *
     * @param data
     */
    void addLocalMedias(List<LocalMedia> data, List<LocalMedia> localMedias) {
        boolean isadd;
        for (int i = 0; i < data.size(); i++) {
            isadd = true;
            for (int j = 0; j < localMedias.size(); j++) {
                if (localMedias.get(j).getCompressPath().equals(data.get(i).getCompressPath())) {
                    isadd = false;
                }
            }
            if (isadd)
                localMedias.add(data.get(i));
        }

    }

    /**
     * 记录上传的地址
     *
     * @param lists
     * @param list
     * @param localMedias
     * @param adapter
     * @param typename
     */
    void upImg(List<LocalMedia> lists, List<File> list,
               List<LocalMedia> localMedias, Proposal2Adapter adapter,
               String typename) {
        for (int i = 0; i < lists.size(); i++) {
            if (lists.get(i) != null && !lists.get(i).getCompressPath().equals("")) {
                list.add(new File(lists.get(i).getCompressPath()));
            }
        }
        businessDao.uploadFiles(list, typename);
        addLocalMedias(lists, localMedias);
        adapter.setList(localMedias, localMedias.size() < 9 ? localMedias.size() + 1 : 9);
    }

    /**
     * 设置已上传照片
     *
     * @param imgString
     * @param imgs
     * @param localMedias
     */
    public static void getImges(String imgString, List<ImageBean> imgs, List<LocalMedia> localMedias) {
        if (imgString.equals("")) {
            return;
        }
        String[] strings = imgString.split(",");
        for (int i = 0; i < strings.length; i++) {
            imgs.add(new ImageBean(strings[i], true));
            LocalMedia media = new LocalMedia();
            media.setCompressed(true);
            media.setCompressPath(strings[i]);
            localMedias.add(media);
        }
    }


    private PopupWindow popupWindow;
    private View popupView;
    private TranslateAnimation animation;

    /**
     * 提示图片
     *
     * @param url
     */
    private void showPop(String url) {
        Tools.lightoff(activity);
        popupView = View.inflate(activity, R.layout.pop_help_img, null);
        popupWindow = new PopupWindow(popupView, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);


        animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0,
                Animation.RELATIVE_TO_PARENT, -1, Animation.RELATIVE_TO_PARENT, 0);
        animation.setInterpolator(new AccelerateInterpolator());
        animation.setDuration(200);

        LinearLayout linearLayout = popupView.findViewById(R.id.ll_back);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        ZoomImageView imageView = popupView.findViewById(R.id.img_help);
        Tools.picassoNetwork(url, imageView);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Tools.lighton(activity);
            }
        });

        popupWindow.showAtLocation(tvTitle, Gravity.CENTER, 0, 0);
        popupView.startAnimation(animation);

    }

}
